import { Ref } from "vue";
import { FormItemRule } from "naive-ui";

export interface IRuleConfig extends FormItemRule {
  msg?: string;
}

interface RuleHandler {
  (value?: IRuleConfig): FormItemRule;
}

export interface IDefaultRules {
  raw: RuleHandler;
  required: RuleHandler;
  numBetween: RuleHandler;
  numMax: RuleHandler;
  numMin: RuleHandler;
  strLenBetween: RuleHandler;
  strLen: RuleHandler;
  strLenMax: RuleHandler;
  strLenMin: RuleHandler;
}

function rulesDefault(): IDefaultRules {
  const raw = (value?: IRuleConfig): FormItemRule => {
    return {
      ...value,
    };
  };

  const required = (value?: IRuleConfig): FormItemRule => {
    let msg = "";
    if (value && value.msg) {
      msg = `[${value.msg}]`;
    }

    return {
      required: true,
      message: "必须输入" + msg,
      trigger: ["blur"],
      ...value,
    };
  };

  const numBetween = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "number",
      message: `只能在 ${value!.min} ~ ${value!.max} 之间`,
      trigger: ["blur"],
      ...value,
    };
  };

  const numMax = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "number",
      message: `只能不大于 ${value!.max} `,
      trigger: ["blur"],
      ...value,
    };
  };

  const numMin = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "number",
      message: `只能不小于 ${value!.min}`,
      trigger: ["blur"],
      ...value,
    };
  };

  const strLenBetween = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "string",
      message: `长度只能在 ${value!.min} ~ ${value!.max} 之间`,
      trigger: ["blur"],
      ...value,
    };
  };

  const strLen = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "string",
      message: `长度必须为 ${value?.len}`,
      trigger: ["blur"],
      ...value,
    };
  };

  const strLenMax = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "string",
      message: `长度应不大于 ${value?.max}`,
      trigger: ["blur"],
      ...value,
    };
  };

  const strLenMin = (value?: IRuleConfig): FormItemRule => {
    return {
      type: "string",
      message: `长度应不小于 ${value?.min}`,
      trigger: ["blur"],
      ...value,
    };
  };

  return {
    raw,
    required,
    numBetween,
    numMax,
    numMin,
    strLenBetween,
    strLen,
    strLenMax,
    strLenMin,
  };
}

export function useFormHandler() {
  const validate = async (form: Ref<any>): Promise<boolean> => {
    return await form.value
      .validate()
      .then(() => {
        return true;
      })
      .catch(() => {
        return false;
      });
  };

  return {
    validate,
    rules: {
      ...rulesDefault(),
    },
  };
}
